<?php
namespace app\user\controller;
use think\Controller;
use app\user\common\Base as commonController;
use think\Db;
use think\Session;
use think\Loader;
//use think\Request;
class Index extends commonController {
	// 初始化方法，赋值高亮导航
	public function _initialize() {

	}
	public function register() {
		return $this ->fetch('login/register');
	}
	public function upload () {
		$file = request()->file('file');
		$qrcode =  request()->param();
//		$qrcode = ($qrcode['qrcode'] == 'true' ? true : false);
		$ckeck = [
			'ext'=>'jpg,png,gif'
		];
		$info = $file->validate($ckeck)->move(ROOT_PATH . 'public' . DS . 'uploads');
		if ($info) {
			$path = DS.'uploads'.DS.$info->getSaveName();
			$pathRes = str_replace("\\","/",$path);
			return [
				"code"=> 0,
				"msg" =>"上传成功",
				"data" => [
				    "src" => $pathRes
				]  
			];
		} else {
			return [
				"code"=> 1,
				"msg" =>"上传失败",
				"data" => $file->getError()
			];
			
		}
        // 移动到框架应用根目录/public/uploads/ 目录下
	}
	public function loginout () {
		Session::delete('user_id');
		Session::delete('user_info');
		return $this -> fetch('login/login');
	}
	public function index() {
		$this -> isLogin();
		$user_id = Session::get('user_id');
		$user = Db::table('user') -> where('id', $user_id) -> find();
		if ($user['is_auth'] == 0) {
			$pre_auth_code = $this->get_pre_auth_code();
			$appId = config('$appId');
			$callback = 'https://edu.qian-hong.com/callback.html';
			$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appId}&pre_auth_code={$pre_auth_code}&redirect_uri={$callback}&auth_type=1";
			$this->assign('url',$url);
			return $this->fetch('login/shouquan');
		} else {
			return $this->fetch('manage/index');
		}
	}

	public function login() {
		$this -> isReadyin();
		return $this -> fetch('login/login');
	}

	public function check() {
		$login_account = input('param.login_account');
		$login_pwd = input('param.login_pwd');
		$res_tel = Db::table('user') -> where('login_account', $login_account) -> find();
		if ($res_tel) {
			$res_pwd = Db::table('user') -> where('login_account', $login_account) -> where('login_pwd', $login_pwd) -> find();
			if ($res_pwd) {
				Session::set('user_id', $res_pwd['id']);
				Session::set('user_info', $res_pwd);
				return ['success' => true, 'msg' => '登录成功'];
			} else {
				return ['success' => false, 'msg' => '密码不正确'];
			}
		} else {
			return ['success' => false, 'msg' => '登录用户不存在'];
		}

	}

	public function ticket() {
		Loader::import('org.wxBizMsgCrypt', EXTEND_PATH);
		$encodingAesKey = config('$encodingAesKey');
		$token = config('$token');
		$appId = config('$appId');
		$timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']);
		$nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']);
		$msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']);
		$encryptMsg = file_get_contents('php://input');
		$data = ['key' => $encryptMsg];
		if ($encryptMsg) {
			file_put_contents('./uploads/test.log', $encryptMsg);
		}
		$pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
		$xml_tree = new \DOMDocument();
		$xml_tree -> loadXML($encryptMsg);
		$array_e = $xml_tree -> getElementsByTagName('Encrypt');
		$encrypt = $array_e -> item(0) -> nodeValue;
		$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
		$from_xml = sprintf($format, $encrypt);

		// 第三方收到公众号平台发送的消息
		$msg = '';
		$errCode = $pc -> decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
		if ($errCode == 0) {
			$xml = new \DOMDocument();
			$xml -> loadXML($msg);
			$array_e = $xml -> getElementsByTagName('ComponentVerifyTicket');
			$component_verify_ticket = $array_e -> item(0) -> nodeValue;
			file_put_contents('./uploads/ticket.log', $component_verify_ticket);
			file_put_contents('./uploads/test_token.log', $component_verify_ticket);
			echo 'success';

		} else {
			file_put_contents('./uploads/error.log', '执行了错误--' . $errCode . '\n', FILE_APPEND);
			print($errCode . "\n");
		}
//		file_put_contents('./uploads/test_token.log', $component_verify_ticket);
		die();
	}
	public function callback ()
	{
		$user_id = Session::get('user_id');
		$auth_code = input('param.auth_code');
		$component_access_token = $this ->get_component_access_token();
		
		$passData = Db::table('user')->where('id',$user_id)->find();//判断是否过期
//		var_dump($passData);
//		die();
		if ((!$passData['expires_in']) || ($passData['expires_in'] < time())) {
			$data = array(
				"component_appid" => config('$appId'), 
				"authorization_code" => $auth_code
			);
			$url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$component_access_token}";
			$send = $this -> https_request($url, json_encode($data));
			$res = json_decode($send, true);
			//根据预授权码获取到授权码等信息
			$authorizer_appid = $res['authorization_info']['authorizer_appid'];
			$expires_in = intval($res['authorization_info']['expires_in']) + time() - 500;
			$authorizer_access_token = $res['authorization_info']['authorizer_access_token'];
			$authorizer_refresh_token = $res['authorization_info']['authorizer_refresh_token'];
			
			Db::table('user')->where('id',$user_id)->update(
				[
					'is_auth' =>1,
					'authorizer_appid' =>$authorizer_appid,
					'expires_in'=>$expires_in,
					'authorizer_access_token'=>$authorizer_access_token,
					'authorizer_refresh_token'=>$authorizer_refresh_token
				]
			);//更新授权状态
			$get_wx_data = array(
				"component_appid" => config('$appId'), 
				"authorizer_appid" => $authorizer_appid
			);
			$get_wx_url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$component_access_token}";
			$get_wx_send = $this -> https_request($get_wx_url, json_encode($get_wx_data));
			$get_wx_res = json_decode($get_wx_send, true);
			$owner_user = Db::table('wechat_public')->where('owner_user',$user_id)->find();
			$owner_data = [
					'owner_user' =>$user_id,
					'nick_name' =>$get_wx_res['authorizer_info']['nick_name'],
					'head_img'=>$get_wx_res['authorizer_info']['head_img'],
					'service_type_info'=>$get_wx_res['authorizer_info']['service_type_info']['id'],
					'verify_type_info'=>$get_wx_res['authorizer_info']['verify_type_info']['id'],
					'user_name'=>$get_wx_res['authorizer_info']['user_name'],
					'principal_name'=>$get_wx_res['authorizer_info']['principal_name'],
					'alias'=>$get_wx_res['authorizer_info']['alias'],
					'qrcode_url'=>$get_wx_res['authorizer_info']['qrcode_url'],
					'authorizer_appid'=>$get_wx_res['authorization_info']['authorizer_appid'],
					'authorizer_refresh_token'=>$get_wx_res['authorization_info']['authorizer_refresh_token']
			];
			if ($owner_user && $owner_user['id']) {
				Db::table('wechat_public')->where('id',$owner_user['id'])->update($owner_data);//更新授权状态
			} else {
				Db::table('wechat_public')->insert($owner_data);
			}
		}		
		$this -> success('授权成功，正在跳转', url('user/Index/index'));

	}
	
}
